<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :checkedit="checkedit"  :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>
<script>
	import {
		buildFormData,
		formValidation,
		changeEditor,
		formShowLoading,
		configFormEditor,
		getWorkCacheKey,
		changeConfigAttr,
		configSelectData,
		formModelLoad,
		hasEditor,
		getEditorTitle,
		getFormFields,
		insertAfterEditor,
		insertEditors
	} from '@/static/js/formUtil.js';
	import dateTimePicker from '@/static/js/dateTimePicker.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	import moment from '@/static/js/moment.js';
	import validation from '@/static/js/formValidation.js';


export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			initValue: {
				parentOthers:"",
				currentOthers:""
			},
			areaCacheKey: 'hr-u-confirm-area-cache',
			parentAddressCacheKey:'hr-u-confirm-parentAddress-cache',
			nationCacheKey:'hr-u-confirm-nation-cache',
			currentAddressCacheKey:'hr-u-confirm-currentAddress-cache',
			posCacheKey:'hr-u-confirm-pos-cache',
			refereeCacheKey:"hr-u-confirm-referee-cache",
			empSupplyList:[]
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId','areaCode','areaName'])
	},
	methods: {
		onSelectPhone(val){
			let _that = this
			let formData = {
				mobile:val
			}
			let rules = [{
				msg:["录入的手机号("+val+")格式错误，请重新输入"],
				name:"mobile",
				rule:["isMobile"]
			}]
			let result = validation.validation(formData,rules)
			if(result){
				_that.om.toast(result)
				_that.$refs.autoform.clear("userInfo","infophone")
			}else{
				_that.om.request(
					"tpiRegister/verifyPhone",
					{
						phone: val,
						idCard: _that.$refs.autoform.formdata.idCard
					}
				).then(res=>{
					if(res.succeed ){
						if(!res.value){
						}else if(res.value.one){
							_that.om.toast(res.value.one)
							_that.$refs.autoform.clear("userInfo","infophone")
						}
					}
				})
			}
		},
		getAdressByIdCard(val){
			let _that = this
			_that.om.request(
				'tpiRegister/getAddressInfoByIdCard',
				{
					idCard:val,
					orgId:_that.orgId
				},
				'post'
			).then(res=>{
				if(res.value){
				_that.$refs.autoform.formdata.parentPlaceId = res.value.parentPlaceId
				_that.$refs.autoform.formdata.parentPlaceName= res.value.parentPlaceName
				_that.$refs.autoform.formdata.registerCategoryId = res.value.registerCategoryId
				_that.$refs.autoform.formdata.registerCategoryName = res.value.registerCategoryName
				_that.$refs.autoform.initSelectIndex('userInfo','registerCategoryId')
				}
			})
		},
		getSexAndBirthDay(val){
			let _that = this
			_that.om.request(
				'tpiRegister/getSexBirth',
				{
					idcard:val,
					orgId:_that.orgId
				}
			).then(res=>{
				if(res.value){
					_that.$refs.autoform.formdata.infosex = res.value[0]=='M'?'男':'女'
					_that.$refs.autoform.formdata.infobirthday = moment(res.value[1]).format('YYYY-MM-DD')
					_that.$refs.autoform.formdata.birthplace = res.value[2]
				}
			})
		},
		onInputIdCard(val){
			let _that = this
			let formData = {
				idCard:val
			}
			let rules = [{
				msg:["身份证输入有误，请重新输入！"],
				name:"idCard",
				rule:["isIdCard"]
			}]
			let result = validation.validation(formData,rules)
			if(result){
				_that.om.toast(result)
				_that.$refs.autoform.clear("userInfo","idCard")
			}else{
				_that.om.request(
					"tpiRegister/verifyIdCard",
					{
						idcard: val
					}
				).then(res=>{
					if(res.succeed ){
						if(res.value.one){
							_that.om.toast(res.value.one)
							_that.$refs.autoform.clear("userInfo","idCard")
						}else{
							this.getAdressByIdCard(val)
							this.getSexAndBirthDay(val)
						}
					}
				})
			}
		},
		formSubmit() {
			let _that = this 
			for(let item of _that.empSupplyList){
				item.remark = _that.formdata[item.itemId]
			}
			_that.formdata.registerplace = ''
			_that.formdata.supplementStr = JSON.stringify(_that.empSupplyList)
			_that.om.formSave('tpiRegister/addTpiRegisterByH5');
		},
		getWorkParam(){
			return {projectId:this.formdata.projectId}
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code), //制表岗位
				urlUtil.sysdictComboboxUrl('20007'), //身份证件类别
				urlUtil.sysdictComboboxUrl('20010'),//政治面貌
				urlUtil.dictZeroComboboxUrl('23594'), //婚姻状况
				urlUtil.sysdictComboboxUrl('23586'),//目前状态
				urlUtil.sysdictComboboxUrl('23590'),//招聘途径
				urlUtil.dictZeroComboboxUrl('37381'),//血型
				{
					url:"temployee/getRoleCategoryList", //角色类别
				},
				urlUtil.sysdictComboboxUrl('38644'),//户籍地类别
				{
					url:'teRegister/getEmpSupplyList'
				},//其他个人补充事项
				urlUtil.sysdictComboboxUrl('38782'),//外语语种
				urlUtil.sysdictComboboxUrl('38787'),//外语水平
				urlUtil.sysdictComboboxUrl('20404'),//计算机水平
				urlUtil.sysdictComboboxUrl('38791'),//身体状况
			];
			var fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:'tpiRegister/getInfo',
					param:{
						id:fileId
					},
					method:"post"
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'), mainData);
				changeEditor('userInfo', 'idTypeId', 'data', configSelectData(res[1], 'id', 'dicname'), mainData);
				changeEditor('userInfo', 'politicalId', 'data', configSelectData(res[2], 'id', 'dicname'), mainData);
				changeEditor('userInfo', 'marriageCode', 'data', configSelectData(res[3], 'code', 'dicname'), mainData);
				changeEditor('customInfo', 'currentStatusId', 'data', configSelectData(res[4], 'id', 'dicname'), mainData);
				changeEditor('userInfo', 'bloodTypeCode', 'data', configSelectData(res[6], 'code', 'dicname'), mainData);
				changeEditor('customInfo', 'recruitInfoApproachId', 'data', configSelectData(res[5], 'id', 'dicname'), mainData);
				if(res[7].length>1){
					changeEditor("customInfo","roleCategoryId","data",configSelectData(res[7],"id","dicname"),mainData)
				}else{
					changeEditor("customInfo","roleCategoryId","data",configSelectData(res[7],"id","dicname",true),mainData)
				}
				changeEditor('userInfo', 'registerCategoryId', 'data', configSelectData(res[8], 'id', 'dicname'), mainData);
				let editors = []
				for(let item of res[9].value){
					let editor ={
						"type": "textarea",
						"title": item.itemName,
						"valueField":item.itemId+'',
						"required":false,
						"prompt":"请点击输入",
						'placeholder':item.remarkPrompt
					}
					editors.push(editor)
				}
				_that.empSupplyList = res[9].value
				insertEditors('title_empSupply',editors,mainData)
				changeEditor('customInfo', 'foreignLanguageId', 'data', configSelectData(res[10], 'id', 'dicname'), mainData);
				changeEditor('customInfo', 'foreignLanguageLevelId', 'data', configSelectData(res[11], 'id', 'dicname'), mainData);
				changeEditor('customInfo', 'computerAbilityId', 'data', configSelectData(res[12], 'id', 'dicname'), mainData);
				changeEditor('customInfo', 'physicalConditionId', 'data', configSelectData(res[13], 'id', 'dicname'), mainData);
				changeEditor('userInfo','infoname',{
					linkParam: {
						initload: true,
						namefield: 'username',
						notefield:'birthPlace',
						extrafield:'mobile',
						url: "teRegister/getUserList",
						cachename: _that.infonameCacheKey,
						placeholder: '请输入姓名、手机号、籍贯'
					}
				}, null, mainData);
				changeEditor('userInfo','areaCode',{//国家或地区选择
					defaultValue:_that.areaCode,
					defaultName:_that.areaName,
					link: '../../public/search/search',
					linkParam: {
						initload: true,
						namefield: 'dicname',
						url: "regions/getCountryList",
						cachename: _that.areaCacheKey,
						placeholder: '请输入名称'
					}
				}, null, mainData);
				changeEditor('userInfo','nationCode',{//民族选择
					link: '../../public/search/search',
					linkParam: {
						other:JSON.stringify({
							code:'20005'
						}),
						initload: true,
						namefield: 'dicname',
						url: urlUtil.dictZeroComboboxUrl().url,
						cachename: _that.nationCacheKey,
						placeholder: '请输入民族'
					}
				}, null, mainData);
				changeEditor('userInfo','parentPlaceId',{//户籍
					link: '../../public/search/search',
					linkParam: {
						other:JSON.stringify({
							classifyCode:'35923'
						}),
						searchfield:'q',
						namefield: urlUtil.addressUrl().namefield,
						url: urlUtil.addressUrl().url,
						cachename: _that.parentAddressCacheKey,
						placeholder: '请输入地址'
					}
				}, mainData);
				insertAfterEditor('userInfo','parentPlaceId',{
					"type": "textarea",
					"title": "详细地址",
					"valueField": "parentOthers",
					"prompt":"请输入",
					"required":false,
				}, mainData)
				changeEditor('userInfo','currentPlaceId',{//现居住地
					link: '../../public/search/search',
					linkParam: {
						other:JSON.stringify({
							classifyCode:'35923'
						}),
						searchfield:'q',
						namefield: urlUtil.addressUrl().namefield,
						url: urlUtil.addressUrl().url,
						cachename: _that.currentAddressCacheKey,
						placeholder: '请输入地址'
					}
				}, mainData);
				insertAfterEditor('userInfo','currentPlaceId',{
					"type": "textarea",
					"title": "详细地址",
					"valueField": "currentOthers",
					"prompt":"请输入",
					"required":false,
				}, mainData)
				changeEditor('posInfo','posId',{
					link: '../../public/pageSearch/pageSearch',
					linkParam: {
						method :'post',
						namefield: 'posname / instname',
						namesplit:' / ',
						extrafield:'interviewResult',
						searchfield:'q',
						url: "tpiRegister/getposList",
						cachename: _that.posCacheKey,
						placeholder: '请输入岗位、机构名称',
					}
				}, mainData);
				
				changeEditor('customInfo','refereeId',{//推荐人
					link: '../../public/pageSearch/pageSearch',
					linkParam: {
						other:JSON.stringify({
							classifyCode:'35923'
						}),
						searchfield:'q',
						namefield: urlUtil.userPageUrl().namefield,
						url: 'temployee/getAutoCombobox1',
						cachename: _that.refereeCacheKey,
						placeholder: '请输入地址'
					}
				}, null, mainData);
				
				if (_that.subEditorObj['eduOrSchool']) {
					changeEditor('eduOrSchool', 'objStrEdu', {
						titleTemplate: '<%= eduEName %>',
					},
					mainData);
				}
				if (_that.subEditorObj['workExp']) {
					changeEditor('workExp', 'objStrWork', {
						titleTemplate: '<%=  orgNameW %>'
					},
					mainData);
				}
				if (_that.subEditorObj['familyMember']) {
					changeEditor('familyMember', 'objStrFamily', {
						titleTemplate: '<%= nameF %>',
						subtitle1Template: '称谓：<%= appellationFName %>',
						subtitle2Template: '单位：<%= companyF %>',
					}, 
					mainData);
				}
				if(_that.subEditorObj["title_pro"]){
					let att = {}
					let configData = _that.subConfigData["title_pro"]
					if(hasEditor("title_pro","proName",configData)){
						att.titleTemplate = '<%= proName %>'
					}
					if(hasEditor("title_pro","proGradeId",configData)){
						let title = getEditorTitle("title_pro","proGradeId",configData)
						att.subtitle1Template =title+':<%= proGradeName %>'
					}
					if(hasEditor("title_pro","issueDate",configData)){
						let title = getEditorTitle("title_pro","issueDate",configData)
						att.subtitle2Template = title+':<%= issueDate %>'
					}
					if(hasEditor("title_pro","certificateIssuingUnit",configData)){
						let title = getEditorTitle("title_pro","certificateIssuingUnit",configData)
						att.subtitle3Template =title+ ':<%= certificateIssuingUnit %>'
					}
					
					changeEditor("title_pro",'objStrPro',att,mainData)
				}
				
				var avatarEditor = {
					"type": "avatarbox",
					"title": "个人头像",
					"valueField": "fileStr",
					"uploadUrl":"uploadFileData/uploadInterimFile.do",
					formData:{
						key:24
					}
				}
				var avatarList = []
				if(fileId){
					if(res[14].value.uploadFileData){
						avatarList = [_that.om.getUrl("uploadFileData/getFile.do?key=24&fileId=" + res[14].value.uploadFileData.id)]
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, 'fileStr', JSON.stringify(res[14].value.uploadFileData))
						_that.$set(_that.formdata, 'fileStr', JSON.stringify(res[14].value.uploadFileData))
					}
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					for(let item of res[9].value){
						fieldArr.push(item.itemId+'')
					}
					//主表赋值
					for(var i in res[14].value.tpiRegister){
						if(fieldArr.includes(i)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[14].value.tpiRegister[i])
								_that.$set(_that.formdata, i, res[14].value.tpiRegister[i])
						}
					}
					for(let item of res[14].value.supplementList){
						if(fieldArr.includes(item.itemId+'')){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, item.itemId+'', item.remark)
							_that.$set(_that.formdata, item.itemId+'',item.remark)
						}
					}
					//教育经历
					if(_that.subEditorObj["eduOrSchool"]){
					var eduList = _that._.cloneDeep(res[14].value.eduList)
					_that.subEditorObj["eduOrSchool"].workList = eduList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStrEdu", JSON.stringify(eduList))
					_that.$set(_that.formdata, "objStrEdu", JSON.stringify(eduList))
					delete res[14].value.eduList
					}
					//工作经历
					if(_that.subEditorObj["workExp"]){
					var workList = _that._.cloneDeep(res[14].value.workList)
					_that.subEditorObj["workExp"].workList = workList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStrWork", JSON.stringify(workList))
					_that.$set(_that.formdata, "objStrWork", JSON.stringify(workList))
					delete res[14].value.eduList
					}
					//家庭成员
					if(_that.subEditorObj["familyMember"]){
						var familyList = _that._.cloneDeep(res[14].value.familyList)
						_that.subEditorObj["familyMember"].workList = familyList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStrFamily", JSON.stringify(familyList))
						_that.$set(_that.formdata, "objStrFamily", JSON.stringify(familyList))
						delete res[14].value.familyList
					}
					if(_that.subEditorObj["title_pro"]){
						var proList = _that._.cloneDeep(res[14].value.proList)
						_that.subEditorObj["title_pro"].workList = proList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStrPro", JSON.stringify(proList))
						_that.$set(_that.formdata, "objStrPro", JSON.stringify(proList))
						delete res[14].value.proList
					}
					_that.$nextTick(function(){
						this.$nextTick(function(){
							this.$refs.autoform.initSelectIndex("topinfo","zposId")
							this.$refs.autoform.initSelectIndex('userInfo', 'idTypeId');
							this.$refs.autoform.initSelectIndex('userInfo', 'politicalId');
							this.$refs.autoform.initSelectIndex('userInfo', 'marriageCode');
							this.$refs.autoform.initSelectIndex('customInfo', 'currentStatusId');
							this.$refs.autoform.initSelectIndex('userInfo', 'bloodTypeCode');
							this.$refs.autoform.initSelectIndex('customInfo', 'recruitInfoApproachId');
							this.$refs.autoform.initSelectIndex("customInfo","roleCategoryId")
							this.$refs.autoform.initSelectIndex("userInfo","registerCategoryId")
							this.$refs.autoform.initSelectIndex("customInfo","foreignLanguageId")
							this.$refs.autoform.initSelectIndex("customInfo","foreignLanguageLevelId")
							this.$refs.autoform.initSelectIndex("customInfo","computerAbilityId")
							this.$refs.autoform.initSelectIndex("customInfo","physicalConditionId")
						})
					})
				}
				avatarEditor['fileList'] = avatarList
				insertAfterEditor('userInfo','infoname',avatarEditor, mainData)
				_that.$nextTick(function(){
					this.$nextTick(function(){
						if(!this.$refs.autoform.formdata.roleCategoryId){
							this.$refs.autoform.formdata.roleCategoryId = res[7][0].id
							this.$refs.autoform.formdata.roleCategoryName = res[7][0].dicname
						}
						this.$refs.autoform.initSelectIndex("customInfo","roleCategoryId")
					})
				})
			},options);
		}
	},
	onLoad(options) {
		this.initLoad(options);
	},
	onUnload(){
		//#ifdef APP-PLUS
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				uni.removeStorage({
					key: getWorkCacheKey(fieldId)
				});
			}
		}
		//#endif
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				let editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.areaCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.areaCode = d.code
						formdata.areaName = d.dicname
						uni.removeStorage({
							key: _that.areaCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.nationCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.nationCode = d.code
						formdata.nationName = d.dicname
						uni.removeStorage({
							key: _that.nationCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.parentAddressCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.parentPlaceId = d.id
						formdata.parentPlaceName = d.fullName
						uni.removeStorage({
							key: _that.parentAddressCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.currentAddressCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.currentPlaceId = d.id
						formdata.currentPlaceName = d.fullName
						uni.removeStorage({
							key: _that.currentAddressCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.posCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.posId = d.posid
						formdata.posName = d.posname
						formdata.instShortName = d.instname
						formdata.orgShortName =d.orgShortName
						formdata.posCareercat =d.careercat
						formdata.salaryWay =d.salaryWay
						formdata.gradeSalaryRange =d.gradeSalaryRange
						formdata.probation =d.probation
						uni.removeStorage({
							key: _that.posCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.refereeCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.refereeId = d.id
						formdata.refereeName = d.userPosInstName
						formdata.refereeMobile = d.mobile
						uni.removeStorage({
							key: _that.refereeCacheKey
						});
					}
				}
			});
		}
	}
};
</script>
<style></style>
